var express = require('express');
var router = express.Router();
var cors = require('cors')

const puppeteer = require('puppeteer');

const fs = require("fs");
const path = require("path");

var xlsx = require('node-xlsx').default;





/* GET home page. */
router.get('/', cors(), async (req, res, next) => {

    res.render('index');



});
router.get('/getPhone', async (req, res) => {


    // var urlPath = fs.readFileSync('path\\p.txt', 'utf8');

    // if (urlPath) {
  
        let pat = "path"
        let status = await fs.existsSync(pat)
        if (!status) {
            await fs.mkdirSync(pat);
        }


    const browser = await puppeteer.launch({

        //  slowMo: 100,    //放慢速度
        ignoreHTTPSErrors: false,
        defaultViewport: {
            width: 1920,
            height: 1000
        },
        headless: true,

        executablePath: "chrome-win\\chrome.exe",
        // executablePath:puppeteer.executablePath(),
        // executablePath: "C:\Program Files/Google/Chrome/Application/chrome.exe",
        // ignoreDefaultArgs: ['--enable-automation'],
        // ignoreDefaultArgs: ['--enable-automation','--no-sandbox', '--disable-setuid-sandbox'],

    });

    const page = await browser.newPage();
    let existsStatus = false
    fs.exists('path\\phone.txt', function (exists) {
        existsStatus = exists

        if (exists) {

            // console.log(11122, urlPath);
        } else {
            fs.writeFileSync('path\\phone.txt', '1', {
                'flag': 'w'
            })
        }
    });
    try {

        await page.goto(req.query.url, {
            timeout: 0
        });
        const html = await page.content();
        let leng = JSON.stringify(html).match(/1(3|4|5|7|8|9)\d{9}/g)

        let htmls;
        if (leng) {
            leng.forEach(v => {
                var regExp = new RegExp(v, "g");
                htmls = JSON.stringify(html).replace(regExp, "")
            })
        } else {
            htmls = html

        }
        let arr = JSON.stringify(htmls).match(/1(3|4|5|7|8|9)\d{9}/g)
        var str = []; //去重
        for (var i = 0, len = arr.length; i < len; i++) {
            !RegExp(arr[i], "g").test(str.join(",")) && (str.push(arr[i]));
        }
        let data = [] // 其实最后就是把这个数组写入excel 
        let title = ['手机号'] //这是第一行 俗称列名 
        data.push(title) // 添加完列名 下面就是添加真正的内容了
        str.forEach((element) => {
            let arrInner = []
            arrInner.push(element)

            data.push(arrInner) //data中添加的要是数组，可以将对象的值分解添加进数组，例如：['1','name','上海']
        });
        // console.log(data);
        const sheetOptions = { '!cols': [{ wch: 30 }] };
    
        try {
            let buffer = xlsx.build([{
                name: 'sheet1',
                data: data
            }], { sheetOptions });
            let pat = 'public'
            if (!fs.existsSync(pat)) {
                fs.mkdirSync(pat);
            }

            if (existsStatus) {
                let urlPath = fs.readFileSync('path\\phone.txt', 'utf8');
         
                let num = parseInt(urlPath.trim()) + 1
                fs.writeFileSync('path\\phone.txt', num.toString(), {
                    'flag': 'w'
                })
                let urlPathA = fs.readFileSync('path\\phone.txt', 'utf8');
                fs.writeFileSync(pat + `\\手机号${urlPathA.toString()}.xlsx`, buffer, {
                    'flag': 'w'
                });
            } else {
                fs.writeFileSync(pat + '\\手机号1.xlsx', buffer, {
                    'flag': 'w'
                });
            }

          
            // const writer = fs.createWriteStream(path.join(path.resolve(__dirname, '..'), 'public') + '\\手机号.xlsx', {
            //     //默认值为w， 通过调用writer.write方法写入数据的时候，会直接覆盖文件所有的内容，
            //     // 即会把文件之前的内容全部再删除，写入新的数据
            //     flags: 'w'
            // })

            // //写入数据到流
            // writer.write(buffer, 'utf8')
            // writer.end()
            res.send({
                code: 200,
                data: data,
                msg: "成功"
            });
        } catch (err) {
            res.send({
                code: 401,
                msg: "失败"
            });
        }

        await browser.close();

    } catch (error) {

        res.send({
            code: 401,
            msg: "请填写正确地址"
        });
    }

    // } else {
    //     res.send({
    //         code: 401,
    //         msg: "请先填写路径"
    //     });
    // }
});

router.get('/getPath', async (req, res) => {

    try {
        let pat = "path"
        let status = await fs.existsSync(pat)
        if (!status) {
            await fs.mkdirSync(pat);
        }


        fs.exists('path\\p.txt', function (exists) {

            if (exists) {
                let urlPath = fs.readFileSync('path\\p.txt', 'utf8');

                res.send({
                    code: 200,
                    data: {
                        url: urlPath.trim()
                    },
                    msg: "获取文件成功"
                });
            } else {
                fs.writeFileSync('path\\p.txt', ' ', {
                    'flag': 'w'
                }, function (error) {
                    if (error) {
                        console.log("文件写入失败", error);
                        return false;
                    }
                    console.log('文件写入成功');
                })
            }
        });



    } catch (e) {

        res.send({
            code: 401,
            msg: "获取失败"
        });
    }



})
router.post('/savePath', async (req, res) => {
    let url = req.body.url
    // if (url) {


    try {
        await fs.writeFileSync('path\\p.txt', url, { 'flag': 'w' });
        res.send({
            code: 200,
            data: "保存文件成功",
            msg: "成功"
        });
    } catch (err) {
        res.send({
            code: 401,
            msg: "保存文件失败"
        });
    }


    // } else {
    //     res.send({
    //         code: 401,
    //         msg: "请先填写路径"
    //     });
    // }
})

/*目录创建 */
function mkdirSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
    return false
}

module.exports = router;